<!--
  IPC通信演示组件
  
  展示Electron中各种进程间通信(IPC)的使用方法
  包括主进程与渲染进程、渲染进程间通信等功能
-->

<template>
  <div class="ipc-demo">
    <!-- 页面标题 -->
    <div class="header">
      <h2>🔄 IPC 通信演示</h2>
      <p class="subtitle">演示 Electron 进程间通信的各种功能</p>
    </div>

    <!-- 功能分组 -->
    <div class="demo-sections">
      
      <!-- 1. 应用信息 -->
      <div class="demo-section">
        <h3>📱 应用信息</h3>
        <div class="controls">
          <button @click="getAppInfo" class="btn btn-primary">获取应用信息</button>
          <button @click="getAppVersion" class="btn btn-secondary">获取版本</button>
        </div>
         <div v-if="appInfo" class="result-box">
           <pre>{{ JSON.stringify(appInfo, null, 2) }}</pre>
         </div>
      </div>

      <!-- 2. 窗口控制 -->
      <div class="demo-section">
        <h3>🪟 窗口控制</h3>
        <div class="controls">
          <button @click="minimizeWindow" class="btn btn-secondary">最小化</button>
          <button @click="toggleMaximize" class="btn btn-secondary">最大化切换</button>
          <button @click="toggleAlwaysOnTop" class="btn btn-secondary">
            {{ alwaysOnTop ? '取消置顶' : '窗口置顶' }}
          </button>
        </div>
      </div>

      <!-- 3. 系统通知 -->
      <div class="demo-section">
        <h3>🔔 系统通知</h3>
        <div class="controls">
          <input 
            v-model="notificationText" 
            placeholder="输入通知内容..."
            class="input"
          >
          <button @click="showNotification" class="btn btn-primary">显示通知</button>
        </div>
      </div>

      <!-- 4. 主题控制 -->
      <div class="demo-section">
        <h3>🎨 主题控制</h3>
        <div class="controls">
          <button @click="getSystemTheme" class="btn btn-secondary">获取系统主题</button>
          <span v-if="systemTheme" class="theme-display">
            当前主题: <strong>{{ systemTheme }}</strong>
          </span>
        </div>
      </div>

      <!-- 5. 本地存储 -->
      <div class="demo-section">
        <h3>💾 本地存储</h3>
        <div class="controls">
          <input 
            v-model="storageKey" 
            placeholder="存储键..."
            class="input"
          >
          <input 
            v-model="storageValue" 
            placeholder="存储值..."
            class="input"
          >
          <button @click="setStorage" class="btn btn-success">保存</button>
          <button @click="getStorage" class="btn btn-primary">读取</button>
          <button @click="deleteStorage" class="btn btn-warning">删除</button>
        </div>
        <div v-if="storageResult" class="result-box">
          <p>{{ storageResult }}</p>
        </div>
      </div>

      <!-- 6. 剪贴板操作 -->
      <div class="demo-section">
        <h3>📋 剪贴板</h3>
        <div class="controls">
          <textarea 
            v-model="clipboardText" 
            placeholder="要复制的文本..."
            class="textarea"
          ></textarea>
          <button @click="writeToClipboard" class="btn btn-success">复制到剪贴板</button>
          <button @click="readFromClipboard" class="btn btn-primary">从剪贴板读取</button>
        </div>
      </div>

      <!-- 7. 网络检测 -->
      <div class="demo-section">
        <h3>🌐 网络状态</h3>
        <div class="controls">
          <button @click="checkNetwork" class="btn btn-primary">检查网络连接</button>
          <div v-if="networkStatus" :class="['network-status', networkStatus.online ? 'online' : 'offline']">
            {{ networkStatus.online ? '🟢 在线' : '🔴 离线' }}
            <span v-if="networkStatus.error"> - {{ networkStatus.error }}</span>
          </div>
        </div>
      </div>

      <!-- 8. 广播通信 -->
      <div class="demo-section">
        <h3>📡 广播通信</h3>
        <div class="controls">
          <input 
            v-model="broadcastChannel" 
            placeholder="频道名称..."
            class="input"
          >
          <input 
            v-model="broadcastMessage" 
            placeholder="广播消息..."
            class="input"
          >
          <button @click="sendBroadcast" class="btn btn-success">发送广播</button>
          <button @click="toggleBroadcastListener" class="btn btn-secondary">
            {{ isListeningBroadcast ? '停止监听' : '监听广播' }}
          </button>
        </div>
        <div v-if="receivedBroadcasts.length > 0" class="result-box">
          <h4>收到的广播消息:</h4>
          <div v-for="(msg, index) in receivedBroadcasts" :key="index" class="broadcast-message">
            <span class="channel">[{{ msg.channel }}]</span>
            <span class="message">{{ msg.data }}</span>
            <span class="time">{{ msg.time }}</span>
          </div>
        </div>
      </div>

      <!-- 9. 自定义事件 -->
      <div class="demo-section">
        <h3>⚡ 自定义事件</h3>
        <div class="controls">
          <input 
            v-model="eventName" 
            placeholder="事件名称..."
            class="input"
          >
          <input 
            v-model="eventData" 
            placeholder="事件数据..."
            class="input"
          >
          <button @click="emitEvent" class="btn btn-success">发送事件</button>
          <button @click="toggleEventListener" class="btn btn-secondary">
            {{ isListeningEvents ? '停止监听' : '监听事件' }}
          </button>
        </div>
        <div v-if="receivedEvents.length > 0" class="result-box">
          <h4>收到的自定义事件:</h4>
          <div v-for="(event, index) in receivedEvents" :key="index" class="event-message">
            <span class="event-name">[{{ event.eventName }}]</span>
            <span class="event-data">{{ event.data }}</span>
            <span class="time">{{ event.time }}</span>
          </div>
        </div>
      </div>

    </div>

    <!-- 消息提示 -->
    <div v-if="message.text" :class="['message', message.type]">
      {{ message.text }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// 响应式数据
const appInfo = ref<any>(null)
const systemTheme = ref<string>('')
const alwaysOnTop = ref(false)
const notificationText = ref('Hello from Electron!')

// 存储相关
const storageKey = ref('test-key')
const storageValue = ref('test-value')
const storageResult = ref('')

// 剪贴板
const clipboardText = ref('Hello Clipboard!')

// 网络状态
const networkStatus = ref<{ online: boolean; error?: string } | null>(null)

// 广播通信
const broadcastChannel = ref('test-channel')
const broadcastMessage = ref('Hello Broadcast!')
const receivedBroadcasts = ref<Array<{ channel: string; data: any; time: string }>>([])
const isListeningBroadcast = ref(false)

// 自定义事件
const eventName = ref('custom-event')
const eventData = ref('Hello Events!')
const receivedEvents = ref<Array<{ eventName: string; data: any; time: string }>>([])
const isListeningEvents = ref(false)

// 消息提示
const message = ref({
  text: '',
  type: 'info'
})

// 方法

/**
 * 获取应用信息
 */
const getAppInfo = async () => {
  try {
    appInfo.value = await window.api.app.getInfo()
    console.log(appInfo.value);
    
    showMessage('成功获取应用信息', 'success')
  } catch (error) {
    showMessage(`获取失败: ${error}`, 'error')
  }
}

/**
 * 获取应用版本
 */
const getAppVersion = async () => {
  try {
    const version = await window.api.app.getVersion()
    appInfo.value = { version }
    console.log(appInfo.value);
    showMessage(`应用版本: ${version}`, 'success')
  } catch (error) {
    showMessage(`获取失败: ${error}`, 'error')
  }
}

/**
 * 最小化窗口
 */
const minimizeWindow = () => {
  window.api.window.minimize()
  showMessage('窗口已最小化', 'info')
}

/**
 * 切换最大化
 */
const toggleMaximize = () => {
  window.api.window.toggleMaximize()
  showMessage('切换最大化状态', 'info')
}

/**
 * 切换窗口置顶
 */
const toggleAlwaysOnTop = () => {
  alwaysOnTop.value = !alwaysOnTop.value
  window.api.window.setAlwaysOnTop(alwaysOnTop.value)
  showMessage(`窗口置顶: ${alwaysOnTop.value ? '开启' : '关闭'}`, 'info')
}

/**
 * 显示通知
 */
const showNotification = () => {
  window.api.notification.show({
    title: 'IPC 演示',
    body: notificationText.value
  })
  showMessage('通知已发送', 'success')
}

/**
 * 获取系统主题
 */
const getSystemTheme = async () => {
  try {
    systemTheme.value = await window.api.theme.getSystemTheme()
    showMessage(`系统主题: ${systemTheme.value}`, 'success')
  } catch (error) {
    showMessage(`获取失败: ${error}`, 'error')
  }
}

/**
 * 保存到存储
 */
const setStorage = async () => {
  try {
    await window.api.storage.set(storageKey.value, storageValue.value)
    storageResult.value = `已保存: ${storageKey.value} = ${storageValue.value}`
    showMessage('保存成功', 'success')
  } catch (error) {
    showMessage(`保存失败: ${error}`, 'error')
  }
}

/**
 * 从存储读取
 */
const getStorage = async () => {
  try {
    const value = await window.api.storage.get(storageKey.value)
    storageResult.value = `读取到: ${storageKey.value} = ${JSON.stringify(value)}`
    showMessage('读取成功', 'success')
  } catch (error) {
    showMessage(`读取失败: ${error}`, 'error')
  }
}

/**
 * 删除存储
 */
const deleteStorage = async () => {
  try {
    await window.api.storage.delete(storageKey.value)
    storageResult.value = `已删除: ${storageKey.value}`
    showMessage('删除成功', 'success')
  } catch (error) {
    showMessage(`删除失败: ${error}`, 'error')
  }
}

/**
 * 写入剪贴板
 */
const writeToClipboard = async () => {
  try {
    await window.api.clipboard.writeText(clipboardText.value)
    showMessage('已复制到剪贴板', 'success')
  } catch (error) {
    showMessage(`复制失败: ${error}`, 'error')
  }
}

/**
 * 从剪贴板读取
 */
const readFromClipboard = async () => {
  try {
    const text = await window.api.clipboard.readText()
    clipboardText.value = text
    showMessage('已从剪贴板读取', 'success')
  } catch (error) {
    showMessage(`读取失败: ${error}`, 'error')
  }
}

/**
 * 检查网络状态
 */
const checkNetwork = async () => {
  try {
    networkStatus.value = await window.api.network.checkConnection()
    showMessage('网络状态已更新', 'info')
  } catch (error) {
    showMessage(`检查失败: ${error}`, 'error')
  }
}

/**
 * 发送广播消息
 */
const sendBroadcast = () => {
  window.api.broadcast.send(broadcastChannel.value, broadcastMessage.value)
  showMessage(`已发送广播: [${broadcastChannel.value}] ${broadcastMessage.value}`, 'success')
}

/**
 * 切换广播监听
 */
const toggleBroadcastListener = () => {
  if (isListeningBroadcast.value) {
    window.api.broadcast.off(broadcastChannel.value)
    isListeningBroadcast.value = false
    showMessage('已停止监听广播', 'info')
  } else {
    window.api.broadcast.on(broadcastChannel.value, (data) => {
      receivedBroadcasts.value.unshift({
        channel: broadcastChannel.value,
        data,
        time: new Date().toLocaleTimeString()
      })
      showMessage('收到广播消息', 'info')
    })
    isListeningBroadcast.value = true
    showMessage('开始监听广播', 'info')
  }
}

/**
 * 发送自定义事件
 */
const emitEvent = () => {
  window.api.events.emit(eventName.value, eventData.value)
  showMessage(`已发送事件: [${eventName.value}] ${eventData.value}`, 'success')
}

/**
 * 切换事件监听
 */
const toggleEventListener = () => {
  if (isListeningEvents.value) {
    // 注意：这里需要在实际使用中实现停止监听的逻辑
    isListeningEvents.value = false
    showMessage('已停止监听事件', 'info')
  } else {
    window.api.events.on(eventName.value, (data) => {
      receivedEvents.value.unshift({
        eventName: eventName.value,
        data,
        time: new Date().toLocaleTimeString()
      })
      showMessage('收到自定义事件', 'info')
    })
    isListeningEvents.value = true
    showMessage('开始监听事件', 'info')
  }
}

/**
 * 显示消息
 */
const showMessage = (text: string, type: string = 'info') => {
  message.value = { text, type }
  setTimeout(() => {
    if (message.value.text === text) {
      message.value.text = ''
    }
  }, 3000)
}

// 生命周期
onMounted(async () => {
  showMessage('IPC 通信演示已就绪', 'success')
  
  // 自动获取一些初始信息
  await getSystemTheme()
  await checkNetwork()
  
  // 监听主题变化
  window.api.theme.onThemeChange((theme) => {
    systemTheme.value = theme
    showMessage(`主题已切换为: ${theme}`, 'info')
  })
})

onUnmounted(() => {
  // 清理监听器
  if (isListeningBroadcast.value) {
    window.api.broadcast.off(broadcastChannel.value)
  }
})
</script>

<style scoped>
.ipc-demo {
  min-height: 100vh;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  box-sizing: border-box;
}

.header {
  text-align: center;
  margin-bottom: 40px;
}

.header h2 {
  color: var(--text-primary, #2c3e50);
  margin: 0;
  font-size: 2.2em;
}

.subtitle {
  color: var(--text-secondary, #7f8c8d);
  margin: 5px 0 0 0;
  font-size: 1.1em;
}

.demo-sections {
  display: grid;
  gap: 30px;
}

.demo-section {
  background: var(--card-bg, #f8f9fa);
  border-radius: 12px;
  padding: 25px;
  border-left: 4px solid var(--primary-color, #3498db);
  box-shadow: var(--shadow-sm, 0 2px 10px rgba(0, 0, 0, 0.1));
  border: 1px solid var(--card-border, transparent);
}

.demo-section h3 {
  margin: 0 0 20px 0;
  color: var(--text-primary, #2c3e50);
  font-size: 1.3em;
}

.controls {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 100px;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow, 0 4px 8px rgba(0, 0, 0, 0.2));
}

.btn-primary {
  background: linear-gradient(45deg, var(--primary-color, #3498db), var(--primary-hover, #2980b9));
  color: var(--text-inverse, white);
  border: 1px solid var(--primary-color, transparent);
}

.btn-secondary {
  background: linear-gradient(45deg, var(--text-secondary, #95a5a6), #7f8c8d);
  color: var(--text-inverse, white);
  border: 1px solid var(--text-secondary, transparent);
}

.btn-success {
  background: linear-gradient(45deg, var(--success-color, #2ecc71), var(--success-hover, #27ae60));
  color: var(--text-inverse, white);
  border: 1px solid var(--success-color, transparent);
}

.btn-warning {
  background: linear-gradient(45deg, var(--warning-color, #f39c12), var(--warning-hover, #e67e22));
  color: var(--text-inverse, white);
  border: 1px solid var(--warning-color, transparent);
}

.input {
  padding: 10px 15px;
  border: 2px solid var(--input-border, #bdc3c7);
  border-radius: 6px;
  font-size: 14px;
  min-width: 150px;
  background: var(--input-bg, white);
  color: var(--text-primary, #333);
}

.input:focus {
  outline: none;
  border-color: var(--primary-color, #3498db);
  box-shadow: var(--input-focus-shadow, 0 0 0 0.2rem rgba(52, 152, 219, 0.25));
}

.textarea {
  padding: 10px 15px;
  border: 2px solid var(--input-border, #bdc3c7);
  border-radius: 6px;
  font-size: 14px;
  min-width: 300px;
  min-height: 80px;
  resize: vertical;
  font-family: inherit;
  background: var(--input-bg, white);
  color: var(--text-primary, #333);
}

.textarea:focus {
  outline: none;
  border-color: var(--primary-color, #3498db);
  box-shadow: var(--input-focus-shadow, 0 0 0 0.2rem rgba(52, 152, 219, 0.25));
}

.result-box {
  background: var(--card-bg, white);
  border-radius: 6px;
  padding: 15px;
  color: var(--primary-color, #007bff);
  border: 1px solid var(--border-color, #dee2e6);
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  max-height: 300px;
  overflow-y: auto;
}

.result-box pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
}

.theme-display {
  background: var(--bg-primary, white);
  padding: 8px 15px;
  border-radius: 20px;
  border: 2px solid var(--primary-color, #3498db);
  color: var(--text-primary, #2c3e50);
}

.network-status {
  padding: 8px 15px;
  border-radius: 20px;
  font-weight: 600;
}

.network-status.online {
  background: var(--success-light, #d4edda);
  color: var(--success-color, #155724);
  border: 2px solid var(--success-color, #28a745);
}

.network-status.offline {
  background: var(--error-light, #f8d7da);
  color: var(--error-color, #721c24);
  border: 2px solid var(--error-color, #dc3545);
}

.broadcast-message, .event-message {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  margin: 5px 0;
  background: #e9ecef;
  border-radius: 6px;
}

.channel, .event-name {
  font-weight: 600;
  color: #007bff;
  background: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.message, .event-data {
  flex: 1;
  color: #495057;
}

.time {
  font-size: 12px;
  color: #6c757d;
}

.message {
  padding: 12px 20px;
  border-radius: 6px;
  margin: 20px 0;
  font-weight: 500;
  border-left: 4px solid;
}

.message.info {
  background: #d1ecf1;
  color: #0c5460;
  border-color: #17a2b8;
}

.message.success {
  background: #d4edda;
  color: #155724;
  border-color: #28a745;
}

.message.error {
  background: #f8d7da;
  color: #721c24;
  border-color: #dc3545;
}

.message.warning {
  background: #fff3cd;
  color: #856404;
  border-color: #ffc107;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ipc-demo {
    padding: 15px;
  }
  
  .controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .input, .textarea, .btn {
    width: 100%;
    min-width: unset;
  }
}
</style>
